#include <queue>

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        if (root == nullptr) {
            return {};
        }
        queue<TreeNode*> queue;
        queue.push(root);
        vector<vector<int>> ans;
        while (!queue.empty()) {
            vector<int> level;
            for (int i = 0, len = queue.size(); i < len; i++) {
                TreeNode*& node = queue.front();
                level.emplace_back(node->val);
                if (node->left != nullptr) {
                    queue.push(node->left);
                }
                if (node->right != nullptr) {
                    queue.push(node->right);
                }
                queue.pop();
            }
            ans.emplace_back(level);
        }
        return ans;
    }
};